package com.jketing.service.ams.sys;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jketing.entity.ams.sys.Function;
import com.jketing.entity.ams.sys.Operation;
import com.jketing.entity.ams.sys.Popedom;
import com.jketing.entity.ams.sys.Role;
import com.jketing.repository.BaseRepository;
import com.jketing.repository.ams.sys.PopedomRepository;
import com.jketing.repository.ams.sys.RoleRepository;
import com.jketing.service.BaseService;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;


/**
 * RoleService	角色服务类
 * 	功能：
 * 			继承扩展服务基类实现子类特有方法及功能；
 * 			如：多表查询和多表操作等；
 * 					可注入其它实体的仓库类或使用jdbc实现Dao调用本地Sql进行多表查询
 * 
 * @author  李荣华
 * @version v1.0
 * @date    2017-12-22
 * @since   Spring-data 1.11.4
 */
@Service
public class RoleService extends BaseService<Role,String> {
	
	/**
	 * repository String按IOC容器管理的Bean类型自动注入模块仓库操作实例 .
	 */
	@Autowired
	private RoleRepository repository;
	/**
	 * popedomRepository String按IOC容器管理的Bean类型自动注入模块仓库操作实例 .
	 */
	@Autowired
	private PopedomRepository popedomRepository;
	
	/**
	 * String按IOC容器管理的Bean名称自动注入服务基类的仓库操作实例
	 * 	 
	 * @param BaseRepository<Function,String> repository
	 * 
	 * @return void
	 */
	@Resource(name="roleRepository")
	public void setBaseRepository(BaseRepository<Role,String> repository) {
		super.setBaseRepository(repository);
	}
	
	/**
	 * getMenu 根据角色得到该角色的所有菜单
	 * 	 
	 *  @param roleId 角色id
	 *  @return List<Function> 返回菜单列表
	 */
	public List<Function> getMenu(String roleId){	
		Role role = repository.findOne(roleId);
		List<Function> menu = new ArrayList<Function>();
		for(Popedom popedom : role.getPopedoms()){
			Function parent = popedom.getFunction().getParent();
			if(!menu.contains(parent)) menu.add(parent);
			if(!menu.contains(popedom.getFunction()))
				menu.add(popedom.getFunction());
		}
		Collections.sort(menu);
		return menu;
	}
	
	/**
	 * getFunList 得到角色的功能列表
	 * 
	 * @param id 角色id
	 * @param List<SysFunction> 角色功能列表
	 */	
	public List<Function> getFunList(String id) {
		Role role = repository.findOne(id);
		List<Function> list = new ArrayList<Function>();	
		for(Popedom popedom : role.getPopedoms()){
			if(!list.contains(popedom.getFunction())) {
				list.add(popedom.getFunction());	
			}
		}
		return list;
	}
	
	/**
	 * getButList 得到角色功能的按纽列表
	 * 
	 * @param roleId 角色id
	 * @param funId 功能id
	 * @return List<Button> 角色功能的按纽列表
	 */	
	public List<Operation> getButList(String roleId,String funId) {
		Role role = repository.findOne(roleId);
		List<Operation> list = new ArrayList<Operation>();		
		for(Popedom popedom : role.getPopedoms()){			
			if(funId.equals(popedom.getFunction().getId()) && popedom.getOperation() !=null && !list.contains(popedom.getOperation())){
				list.add(popedom.getOperation());
			}	
		}
	    return list;
	}
	
	/**
	 * getFunButJson 角色功能和按纽json 数据
	 * 
	 * @param roleId 角色id
	 * @param funList 角色功能列表
	 * @return StringBuilder 角色功能和按纽json 数据
	 */	
	public StringBuilder getFunButJson(String roleId,List<Function> funList) {
		StringBuilder sb = new StringBuilder();				
		for(Function sf : funList){	
			if(sb.length()>0) sb.append("^");
			sb.append(sf.getId() + "|");	
			StringBuilder tb = new StringBuilder();
			tb.append("[");
			for(Operation bt : getButList(roleId,sf.getId())){
				if(tb.length()>2) tb.append(",");
				tb.append("{'butId':'" + bt.getId() + "','butName':'" + bt.getName() + "'}");
			}
			tb.append("]");
			sb.append(tb.toString());		
		}
	    return sb;
	}
	
	/**
	 * 保存 角色
	 * 
	 * @param Role entity 角色对象
	 * @param configJson json格式的功能和按纽数据
	 * @return Role 返回保存对象
	 */
	public Role save(Role entity,String configJson){
		entity.setId(getTimeId());
		Role role = repository.save(entity);		
		if(StringUtils.isNotBlank(configJson)) {
			JSONArray ja = JSONArray.fromObject(configJson);
			for(int i=0;i<ja.size();i++){
				JSONObject jo = ja.getJSONObject(i);
				String funId = jo.getString("funId");		
				Function function = new Function();
				function.setId(funId);
				if(jo.get("butList") != JSONNull.getInstance()){
					JSONArray ta = jo.getJSONArray("butList");
					if(ta.size() > 0){
						for(int j=0;j<ta.size();j++){
							Popedom popedom = new Popedom();
							popedom.setId(getTimeId());
							popedom.setFunction(function);
							JSONObject to = ta.getJSONObject(j);
							String butId = to.getString("butId");	
							Operation button = new Operation();
							button.setId(butId);
							popedom.setOperation(button);
							popedom.setRole(role);
							popedomRepository.save(popedom);
						}
					}
					else{
						Popedom popedom = new Popedom();
						popedom.setId(getTimeId());
						popedom.setFunction(function);
						popedom.setRole(role);
						popedomRepository.save(popedom);
					}
				}
				else{
					Popedom popedom = new Popedom();
					popedom.setId(getTimeId());
					popedom.setFunction(function);
					popedom.setRole(role);
					popedomRepository.save(popedom);
				}
			}
		}
		return role;
	}
	
	/**
	 * update 更新角色
	 * 
	 * @param object 角色对象
	 * @param configJson json格式的功能和按纽数据
	 * @return Role 返回更新后对象
	 */
	public Role update(Role entity,String configJson){	
		Role role = repository.saveAndFlush(entity);
		for(Popedom popedom : role.getPopedoms()){
			popedomRepository.delete(popedom);
		}
		if(StringUtils.isNotBlank(configJson)) {
			JSONArray ja = JSONArray.fromObject(configJson);
			for(int i=0;i<ja.size();i++){
				JSONObject jo = ja.getJSONObject(i);
				String funId = jo.getString("funId");		
				Function function = new Function();
				function.setId(funId);
				if(jo.get("butList") != JSONNull.getInstance()){
					JSONArray ta = jo.getJSONArray("butList");
					if(ta.size() > 0){
						for(int j=0;j<ta.size();j++){
							Popedom popedom = new Popedom();
							popedom.setId(getTimeId());
							popedom.setFunction(function);
							JSONObject to = ta.getJSONObject(j);
							String butId = to.getString("butId");	
							Operation button = new Operation();
							button.setId(butId);		
							popedom.setOperation(button);
							popedom.setRole(role);
							popedomRepository.save(popedom);
						}
					}
					else{
						Popedom popedom = new Popedom();
						popedom.setId(getTimeId());
						popedom.setFunction(function);
						popedom.setRole(role);					
						popedomRepository.save(popedom);
					}
				}
				else{
					Popedom popedom = new Popedom();
					popedom.setId(getTimeId());
					popedom.setFunction(function);
					popedom.setRole(role);
					popedomRepository.save(popedom);
				}
			}
		}
		return role;
	}
	
	/**
	 * 删除对象
	 * 
	 * @param ids id串,形如:1,2,3
	 * @return
	 */	
	public void delete(String ids) {
		if(StringUtils.isNotBlank(ids)){
			String[] array = ids.split(",");
			for(int i=0;i<array.length;i++){
				Role role = repository.findOne(array[i]);
				for(Popedom popedom : role.getPopedoms()){
					popedomRepository.delete(popedom);
				}	
				repository.delete(role);
			}
		}
	}
}
